﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
using CourseManagerModels;
using CourseManagerBLL;


namespace CourseManageUI
{
    public partial class FrmAddCourse : Form
    {
        private CourseCategoryManager courseCategoryManager = new CourseCategoryManager();
        private CourseManager courseManager = new CourseManager();
        List<Course> tempCourse = new List<Course>();//临时课程，直接加入ui页面
        public FrmAddCourse()
        {
            InitializeComponent();
            //设置下拉框数据源
            this.cbbCategory.DataSource = courseCategoryManager.GetCourseCategories();
            //设置展示给用户的数据(CourseCategory.cs中的字段名)
            this.cbbCategory.DisplayMember = "CategoryName";
            //设置用户选择后传递的值
            this.cbbCategory.ValueMember = "CategoryId";

            //禁止自动生成列
            this.dgvCourseList.AutoGenerateColumns = false;
        }
        
        //保存到数据库
		private void btnSaveToDB_Click(object sender, EventArgs e)
		{
            //数据校验
            if (this.txtCourseName.Text.Trim().Length==0)
			{
                MessageBox.Show("请输入课程名称");
                this.txtCourseName.Focus();
                return;
            }
            if(this.txtClassHour.Text.Trim().Length == 0)
			{
                MessageBox.Show("请输入课程总数");
                this.txtClassHour.Focus();
                return;
            }
            if (this.txtCredit.Text.Trim().Length == 0)
            {
                MessageBox.Show("请输入课程学分");
                this.txtCredit.Focus();
                return;
            }
            if (this.txtCourseContent.Text.Trim().Length == 0)
            {
                MessageBox.Show("请输入内容概述");
                this.txtCourseContent.Focus();
                return;
            }
            //ComboBox组件在没有选择任何项的时候，其SelectedIndex属性通常是-1
            if (this.cbbCategory.SelectedIndex == -1)
            {
                MessageBox.Show("请选择类别");
                this.cbbCategory.Focus();
                return;
            }

            //封装数据,这里
            Course course = new Course
            {
                CourseName = this.txtCourseName.Text.Trim(),
                ClassHour = Convert.ToInt32(this.txtClassHour.Text.Trim()),
                Credit = Convert.ToInt32(this.txtCredit.Text.Trim()),
                CourseContent = this.txtCourseContent.Text.Trim(),
                CategoryId = Convert.ToInt32(this.cbbCategory.SelectedValue),
                TeacherId = 1000,
                CategoryName = this.cbbCategory.Text //该属性用于UI界面显示，不用于数据库
               
            };
            //存储数据
            int result = courseManager.AddCourse(course);

            //存储失败则退出
			if (result <= 0)
			{
                return;
			}
            //设置刚刚加入的课程到前端
            tempCourse.Add(course);
            this.dgvCourseList.DataSource = null;
            this.dgvCourseList.DataSource = this.tempCourse;
            
            
        }
	}
}
